<?php if (!defined("BASEPATH")) exit("No direct script access allowed");

class Admin_lte extends MY_Controller {

	function __construct() {

		parent::__construct();
		if(!(Common::isAdmin() or Common::isSuperAdmin()) and $this->uri->segment(2) != "login") {
			$this->session->sess_destroy();
			$this->db->query("commit");
			redirect("admin_lte/login");
		}
		$this->db->cache_off();

		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false );
		header("Pragma: no-cache");

		$this->load->model("usr2ent");
		$this->load->model("city");
		$this->load->model("country");
		$this->load->model("institute");
		$this->load->model("institute_address");
		$this->load->model("ent2cat");
		$this->load->model("ent2image");
		$this->load->model("user");
		$this->load->model("category");
		$this->load->model("ent2cat");
		$this->load->model("major");
		$this->load->model("daemonc_model");
		$this->load->model("accomodation");
		$this->load->model("acc2ins_maj");
		$this->load->model("currency");
		$this->load->model("scholarship");
		$this->load->model("sch2cou_ins_maj");
		$this->load->model("subject");
		$this->load->model("usr2ent");
		$this->load->model("message");
		$this->load->model("article_model");
		$this->load->model("group");
		$this->load->model("usr2grp");
		$this->load->model("ent2art");

		if(Common::isAdmin()) {
			$this->getUsr2ent = $this->usr2ent->getUsr2ent("u2e_usr_id = '".$this->session->userdata("usrId")."'");
		}

		$this->page["content"] = $this->load->view("modal", NULL, TRUE);

	}

	function get_unread_messages() {
		$this->db->cache_off();
		$this->load->model("usr2ent");
		$this->load->model("message");
		if(Common::isAdmin()) {
			$getUsr2ent = $this->usr2ent->getUsr2ent("u2e_usr_id = '".$this->session->userdata("usrId")."'");
			$getUsr2entINS = (($getUsr2ent and isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array(0)));
			$this->page["getUnreadMessagesCnt"] = $this->message->getUnreadMessagesCnt($where = "mes_ins_id in (".implode(",", $getUsr2entINS).") and mes_sender_usr_id != ".$this->session->userdata("usrId"));
			if($this->page["getUnreadMessagesCnt"]) {
				$this->page["getUnreadMessages"] = $this->message->getUnreadMessages($where = "mes_ins_id in (".implode(",", $getUsr2entINS).") and mes_sender_usr_id != ".$this->session->userdata("usrId"));
			}
			$this->page["content"] = $this->load->view("admin/partials//messages_box", $this->page, TRUE);
			$this->load->view("template/empty", $this->page);
		}
	}

	function load_chart() {
		$this->load->view("admin/dashboard_chart_lte");
	}

	function index() {
		$this->page["lte_title"] = $this->lang->line("DASHBOARD");
		$this->page["content"] .= $this->load->view("admin/dashboard_lte", NULL, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function login() {
		if(!$this->session->userdata("usrId")) {
			if($this->input->post("password") and $this->input->post("email")) {
				$getUser = $this->user->getUser("usr_email = '".$this->db->escape_str($this->input->post("email"))."' and usr_password = '".md5($this->input->post("password"))."' and usr_verify is null");
				if($getUser) {
					$getUser = current($getUser);
					$this->session->set_userdata("usrId", $getUser["usrId"]);
					$this->session->set_userdata("usrEmail", $getUser["usrEmail"]);
					$this->session->set_userdata("usrNewsletter", $getUser["usrNewsletter"]);
					$this->session->set_userdata("grpName", $getUser["grpName"]);
					$this->session->set_userdata("usrProvider", $getUser["usrProvider"]);
					$this->session->set_userdata("fullName", $getUser["fullName"]);
					$this->user->update($getUser["usrId"], array("usr_logged" => $getUser["usrLogged"]+1));
					$this->db->trans_complete();
					redirect("admin_lte/index");
				}
			}
			$this->page["bodyClass"] = "login-page";
			$this->page["content"] .= $this->load->view("admin/login_lte", NULL, TRUE);
			$this->load->view("template/blank_lte", $this->page);
		} else {
			redirect("admin/index");
		}
	}

	function schools() {
		if(!(Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_IMP")))
			redirect("admin_lte");

		$this->page["lte_title"] = $this->lang->line("SCHOOLS");

		$where = "ins_ins_id is null";
		//define("ENTITY", "INS");
		$this->page["instituteList"] = $this->institute->getInstitute($where);

		$this->page["content"] .= $this->load->view("admin/schools_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function faculties($parentInsUrlName = null) {
		if(!(Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_FAC")))
			redirect("admin_lte");

		$this->page["lte_title"] = $this->lang->line("FACULTIES");

		$where = "ins_ins_id is not null";
		if(!is_null($parentInsUrlName)) {
			$this->page["parentIns"] = $this->institute->getInstitute("ins_url_name = '".$this->db->escape_str($parentInsUrlName)."'");
			if($this->page["parentIns"]) {
				$this->page["breadcrumb"]["admin_lte/faculties"] = $this->page["lte_title"];
				$this->page["lte_title"] = $this->page["parentIns"][0]["insName"]." ".strtolower($this->lang->line("FACULTIES"));
				$where .= " and ins_ins_id = ".$this->page["parentIns"][0]["insId"];
			}
		}
		define("ENTITY", "FAC");
		$this->page["instituteList"] = $this->institute->getInstitute($where);

		$this->page["content"] .= $this->load->view("admin/faculties_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function majors($insId = NULL, $majPresenter = NULL) {
		if(!(Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_MAJ")))
			redirect("admin_lte");

		if(!is_numeric($insId)) {
			$insId = NULL;
			$majPresenter = $insId;
		}

		$this->page["lte_title"] = $this->lang->line("MAJORS");

		$this->page["majorList"] = $this->major->getMajor($where = (($insId)?("ins_id = '".intval($insId)."'"):("")).($majPresenter ? ($insId ? " and " : "") . "maj_presenter = '".$this->db->escape_str($majPresenter)."'" : ""));

		$this->page["content"] .= $this->load->view("admin/majors_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function accomodations() {
		if(!(Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_ACC")))
			redirect("admin_lte");

		$this->page["lte_title"] = $this->lang->line("ACCOMODATIONS");

		$this->page["accomodationList"] = $this->accomodation->getAccomodation();

		$this->page["content"] .= $this->load->view("admin/acoomodations_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function scholarships() {
		if(!(Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_SCH")))
			redirect("admin_lte");

		$this->page["lte_title"] = $this->lang->line("SCHOLARSHIPS");

		$this->page["scholarshipList"] = $this->scholarship->getScholarship();

		$this->page["content"] .= $this->load->view("admin/scholarships_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function entity_edit() {
		$getCategoryVal = $this->category->getCategoryVal($this->input->post("ENTITY"), $this->input->post("ID"));

		// temp adatokkal feluliras
		foreach($getCategoryVal as $catId => $catData) {
			if($catData["e2cTempFlag"] == "I") {
				$getCategoryVal[$catId]["val"] = $catData["e2cTemp"];
			}
		}
		$this->page["getCategoryVal"] = $getCategoryVal;

		switch($this->input->post("ENTITY")) {

			case "FAC": {
				define("ENTITY", "FAC");
				$this->page["getInstituteList"] = array();
				$getInstituteList = $this->institute->getInstitute();
				foreach($getInstituteList as $ins) {
					$this->page["getInstituteList"][$ins["insId"]] = $ins["insName"]." (".$ins["cityName"]." - ".$ins["couName"].")";
				}
			}

			case "INS": {
				$this->page["getInstitute"] = $this->institute->getInstitute("ins_id = '".$this->db->escape_str($this->input->post("ID"))."'");

				$tmpGetCategoryVal = array();
				foreach($getCategoryVal as $catId => $catData) {
					$tmpGetCategoryVal[$catId] = $catData;

					if($this->input->post("ID") == -1) {
						if($catId == $this->config->item("categoryINSAddress")) {
							$tmpGetCategoryVal[$catId]["val"] = $this->input->post("insAddress");
						}
						if($catId == $this->config->item("categoryINSWeb")) {
							$tmpGetCategoryVal[$catId]["val"] = $this->input->post("insWeb");
						}
						if($catId == $this->config->item("categoryINSPostalCode")) {
							$tmpGetCategoryVal[$catId]["val"] = $this->input->post("insPostalCode");
						}
					}

					if($catId == $this->config->item("categoryINSAddress") or $catId == $this->config->item("categoryFACAddress")) {

						$tmpGetCategoryVal[$catId]["catName"] .= " (<span id=\"marker\"><span class=\"glyphicon glyphicon-map-marker\" title=\"".$this->lang->line("SEE_ON_MAP")."\"></span> ".$this->lang->line("SEE_ON_MAP")."</span>)";

						$tmpGetCategoryVal["ins_latitude"] = array(
							"catName" => $this->lang->line("LATITUDE"),
							"catType" => "C",
							"catRequired" => "N",
							"catList" => null, 
							"val" => isset($this->page["getInstitute"][0]["insLatitude"]) ? $this->page["getInstitute"][0]["insLatitude"] : null,
							"e2cTemp" => null,
							"e2cTempFlag" => "N",
						);
						$tmpGetCategoryVal["ins_longitude"] = array(
							"catName" => $this->lang->line("LONGITUDE"),
							"catType" => "C",
							"catRequired" => "N",
							"catList" => null, 
							"val" => isset($this->page["getInstitute"][0]["insLongitude"]) ? $this->page["getInstitute"][0]["insLongitude"] : null,
							"e2cTemp" => null,
							"e2cTempFlag" => "N",
						);
					}

				}
				$this->page["getCategoryVal"] = $tmpGetCategoryVal;
				//Common::pr($this->page["getCategoryVal"]);

				$this->load->view("admin/editortemplate/institute", $this->page);
			} break;

			case "MAJ": {
				$this->page["getMajor"] = $this->major->getMajor("maj_id = '".$this->db->escape_str($this->input->post("ID"))."'");
				$getInstituteList = $this->institute->getInstitute();
				foreach($getInstituteList as $ins) {
					$this->page["getInstituteList"][$ins["insId"]] = $ins["insName"]." (".$ins["cityName"]." - ".$ins["couName"].")";
				}

				$this->page["getSubjectList"] = $this->subject->getSubject();
				$this->page["szotar"] = Common::szotar(array("PROGTYPE", "PROGTYPE_2"));

				$this->load->view("admin/editortemplate/major", $this->page);
			} break;

			case "ACC": {
				$this->page["getAccomodation"] = $this->accomodation->getAccomodation("acc_id = '".$this->db->escape_str($this->input->post("ID"))."'");

				$getInstituteList = $this->institute->getInstitute();
				foreach($getInstituteList as $ins) {
					$this->page["getInstituteList"][$ins["insId"]] = $ins["insName"]." (".$ins["cityName"]." - ".$ins["couName"].")";
				}

				$tmpGetCategoryVal = array();
				foreach($getCategoryVal as $catId => $catData) {
					$tmpGetCategoryVal[$catId] = $catData;

					if($catId == $this->config->item("categoryACCAddress")) {

						$tmpGetCategoryVal[$catId]["catName"] .= " (<span id=\"marker\"><span class=\"glyphicon glyphicon-map-marker\" title=\"".$this->lang->line("SEE_ON_MAP")."\"></span> ".$this->lang->line("SEE_ON_MAP")."</span>)";

						$tmpGetCategoryVal["acc_latitude"] = array(
							"catName" => $this->lang->line("LATITUDE"),
							"catType" => "C",
							"catRequired" => "N",
							"catList" => null, 
							"val" => isset($this->page["getAccomodation"][0]["accLatitude"]) ? $this->page["getAccomodation"][0]["accLatitude"] : null,
							"e2cTemp" => null,
							"e2cTempFlag" => "N",
						);
						$tmpGetCategoryVal["acc_longitude"] = array(
							"catName" => $this->lang->line("LONGITUDE"),
							"catType" => "C",
							"catRequired" => "N",
							"catList" => null, 
							"val" => isset($this->page["getAccomodation"][0]["accLongitude"]) ? $this->page["getAccomodation"][0]["accLongitude"] : null,
							"e2cTemp" => null,
							"e2cTempFlag" => "N",
						);
					}

				}
				$this->page["getCategoryVal"] = $tmpGetCategoryVal;
				//Common::pr($this->page["getCategoryVal"]);

				$this->load->view("admin/editortemplate/accomodation", $this->page);
			} break;

 			case "SCH": {
				$this->page["getScholarship"] = $this->scholarship->getScholarship("sch_id = '".$this->db->escape_str($this->input->post("ID"))."'");

				define("ENTITY", "SCH");
				$getInstituteList = $this->institute->getInstitute();
				foreach($getInstituteList as $ins) {
					$this->page["getInstituteList"][$ins["insId"]] = $ins["insName"]." (".$ins["cityName"]." - ".$ins["couName"].")";
				}

				$getMajorList = $this->major->getMajor();
				foreach($getMajorList as $maj) {
					$this->page["getMajorList"][$maj["majId"]] = $maj["majName"]." (".$maj["insName"].")";
				}

				$this->page["getCountryList"] = $this->get_country();

				$this->page["getSubjectList"] = $this->subject->getSubject();

				$this->load->view("admin/editortemplate/scholarship", $this->page);
			} break;

			case "USER": {
				$this->page["getUser"] = $this->user->getUser("usr_id = '".$this->db->escape_str($this->input->post("ID"))."'");

				$where = null;
				if(Common::isAdmin())
					$where = "grp_id <> 1";
				$getGroupList = $this->group->getGroup($where);
				$this->page["getGroupList"] = array();
				foreach($getGroupList as $grp) {
					$this->page["getGroupList"][$grp["grpId"]] = $grp["grpName"];
				}

				$this->page["getCountryList"] = $this->get_country();

				$getInstituteList = $this->institute->getInstitute();
				foreach($getInstituteList as $ins) {
					$this->page["getInstituteList"][$ins["insId"]] = $ins["insName"]." (".$ins["cityName"]." - ".$ins["couName"].")";
				}

				$this->page["getSubjectList"] = $this->subject->getSubject();

				$majorList = $this->major->getMajor();
				$this->page["majorList"] = array();
				foreach($majorList as $maj) {
					$this->page["majorList"][$maj["majId"]] = $maj["majName"]." (".$maj["insName"].")";
				}

				$this->load->view("admin/editortemplate/user", $this->page);
			} break;

		}

	}

	function entity_insert_update() {

		$response = array("error" => "");

		if($this->input->get_post("publish") !== FALSE) {

			$getEnt2cat = $this->ent2cat->getEnt2cat($where = "e2c_entity = '".$this->db->escape_str($this->input->get_post("ENTITY"))."' and e2c_ent_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
			foreach($getEnt2cat as $d) {
				if($d["e2cTempFlag"] == "I" or $this->input->get_post("publish") == 2) {
					$insUpd = array(
						"e2c_temp" => NULL,
						"e2c_temp_flag" => "N",
					);
					if($this->input->get_post("publish") == 1) {
						$insUpd["e2c_int"] = ((is_numeric($d["e2cTemp"]))?($d["e2cTemp"]):(NULL));
						$insUpd["e2c_text"] = ((!is_numeric($d["e2cTemp"]))?(preg_replace('/class=".*?"/', '', $d["e2cTemp"])):(NULL));
					} elseif($this->input->get_post("publish") == 2) {
						$insUpd["e2c_int"] = NULL;
						$insUpd["e2c_text"] = NULL;
						$insUpd["e2c_temp"] = Common::coalesce(array($d["e2cInt"], $d["e2cText"], $d["e2cTemp"]));
						$insUpd["e2c_temp_flag"] = "I";
					}
					$this->ent2cat->update($d["e2cId"], $insUpd);
				}
			}

			$this->daemonc_model->runDaemonc();

		} else {

			switch($this->input->post("ENTITY")) {

				case "INS": {
					if($this->input->get_post("del")) {
						$getMajor = $this->major->getMajor($where = "maj_ins_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
						foreach($getMajor as $majData) {
							$this->major->delete($majData["majId"]);
						}
						$this->institute->delete($this->input->get_post("ID"));
						// karok törlése
						$getChildren = $this->institute->getChildren($this->input->get_post("ID"));
						foreach($getChildren as $ins) {
							if(isset($ins["insId"])) {
								$this->institute->delete($ins["insId"]);
							}
						}
					} else {

						if(!$this->input->get_post("ins_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("ins_city_id")) {
							$response["error"] .= $this->lang->line("CITY_IS_REQUIRED")."<br/>";
						}

						if($this->input->get_post("ins_ins_id") and $this->input->get_post("ins_ins_id") === $this->input->get_post("ID")) {
							$response["error"] .= $this->lang->line("PARENT_DOES_NOT_MATCH_WITH_THE_SELECTED_INSTITUTE")."<br/>";
						}

						if(!$response["error"]) {
							$insUpd = array(
								"ins_ins_id" => (($this->input->get_post("ins_ins_id"))?($this->input->get_post("ins_ins_id")):(NULL)),
								"ins_name" => $this->input->get_post("ins_name"),
								"ins_url_name" => my_url_title($this->input->get_post("ins_name"), "underscore", TRUE),
								"ins_city_id" => $this->input->get_post("ins_city_id"),
								"ins_latitude" => (($this->input->get_post("ins_latitude"))?($this->input->get_post("ins_latitude")):(NULL)),
								"ins_longitude" => (($this->input->get_post("ins_longitude"))?($this->input->get_post("ins_longitude")):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->institute->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->institute->insert($insUpd);
							}
							$this->institute->fixUrlNames();

							if(!defined("AUTH_ERROR")) {
								$this->entity_category_insert_update($this->input->post("ENTITY"), abs($this->input->get_post("ID")));
							}

						}
					}
				} break;

				case "MAJ": {
					if($this->input->get_post("del")) {
						$this->major->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("maj_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_COURSE_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_ins_id")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_sub_id")) {
							$response["error"] .= $this->lang->line("SUBJECT_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_prog_type")) {
							$response["error"] .= $this->lang->line("TYPE_OF_THE_SCHOOL_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_prog_type2")) {
							$response["error"] .= $this->lang->line("PROGRAM_TYPE_IS_REQUIRED")."<br/>";
						}

						if(!$response["error"]) {

							$tmp_url_name = $url_name = my_url_title($this->input->get_post("maj_name"), "underscore", TRUE);
							$free = FALSE;
							$counter = 1;
							while(!$free) {
								$free = TRUE;
								$getMajor = $this->major->getMajor($where = "maj_url_name = '".$this->db->escape_str($url_name)."'".(($this->input->get_post("ID") > 0)?(" and maj_id <> '".$this->db->escape_str($this->input->get_post("ID"))."' "):("")));
								if($getMajor) {
									$free = FALSE;
									$url_name = $tmp_url_name.$counter;
									$counter++;
								}
							}

							$insUpd = array(
								"maj_name" => $this->input->get_post("maj_name"),
								"maj_url_name" => $url_name, //my_url_title($this->input->get_post("maj_name"), "underscore", TRUE),
								"maj_ins_id" => $this->input->get_post("maj_ins_id"),
								"maj_sub_id" => $this->input->get_post("maj_sub_id"),
								"maj_prog_type" => $this->input->get_post("maj_prog_type"),
								"maj_prog_type2" => $this->input->get_post("maj_prog_type2"),
								"maj_list_from_date" => (($this->input->get_post("maj_list_from_date"))?(Common::dateToDatabase($this->input->get_post("maj_list_from_date"))):(NULL)),
								"maj_list_till_date" => (($this->input->get_post("maj_list_till_date"))?(Common::dateToDatabase($this->input->get_post("maj_list_till_date"))):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->major->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->major->insert($insUpd);
							}
							
							// acc
							$getAcc2ins_majIds = $this->acc2ins_maj->getAcc2ins_majIds($where = "a2im_maj_id = ".intval($_POST["ID"]));

							foreach($getAcc2ins_majIds as $a2imId => $d) {
								$this->acc2ins_maj->delete($a2imId);
							}
							if($this->input->post("acc_id")) {
								foreach($this->input->post("acc_id") as $accId) {
									if($accId) {
										$this->acc2ins_maj->insert(array("a2im_acc_id" => $accId, "a2im_maj_id" => $this->input->get_post("ID")));
									}
								}
							}
							
							if(!defined("AUTH_ERROR")) {
								$this->entity_category_insert_update($this->input->post("ENTITY"), abs($this->input->get_post("ID")));
							}

						}
					}
				} break;

				case "FAC": {
					if($this->input->get_post("del")) {
						$getMajor = $this->major->getMajor($where = "maj_ins_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
						foreach($getMajor as $majData) {
							$this->major->delete($majData["majId"]);
						}
						$this->institute->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("ins_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("ins_city_id")) {
							$response["error"] .= $this->lang->line("CITY_IS_REQUIRED")."<br/>";
						}

						if($this->input->get_post("ins_ins_id") and $this->input->get_post("ins_ins_id") === $this->input->get_post("ID")) {
							$response["error"] .= $this->lang->line("PARENT_DOES_NOT_MATCH_WITH_THE_SELECTED_INSTITUTE")."<br/>";
						}

						if(!$response["error"]) {
							$insUpd = array(
								"ins_ins_id" => (($this->input->get_post("ins_ins_id"))?($this->input->get_post("ins_ins_id")):(NULL)),
								"ins_name" => $this->input->get_post("ins_name"),
								"ins_url_name" => my_url_title($this->input->get_post("ins_name"), "underscore", TRUE),
								"ins_city_id" => $this->input->get_post("ins_city_id"),
								"ins_latitude" => (($this->input->get_post("ins_latitude"))?($this->input->get_post("ins_latitude")):(NULL)),
								"ins_longitude" => (($this->input->get_post("ins_longitude"))?($this->input->get_post("ins_longitude")):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->institute->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->institute->insert($insUpd);
								if(Common::isAdmin()) {
									$this->usr2ent->insert(
										array(
											"u2e_usr_id" => $this->session->userdata("usrId"),
											"u2e_ins_id" => $_POST["ID"],
										)
									);
									$this->usr2ent->insert(
										array(
											"u2e_usr_id" => $this->session->userdata("usrId"),
											"u2e_ins_id" => $_POST["ID"],
											"u2e_page_cat" => "FAC",
										)
									);
								}
							}
							$this->institute->fixUrlNames();

							if(!defined("AUTH_ERROR")) {
								$this->entity_category_insert_update($this->input->post("ENTITY"), abs($this->input->get_post("ID")));
							}

						}
					}
				} break;

				case "ACC": {
					if($this->input->get_post("del")) {
						$this->accomodation->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("acc_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_ACCOMODATION_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("acc_city_id")) {
							$response["error"] .= $this->lang->line("CITY_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("ins_id")) {
							$response["error"] .= $this->lang->line("THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}
						
						if(!$response["error"]) {
							$insUpd = array(
								"acc_name" => $this->input->get_post("acc_name"),
								"acc_url_name" => my_url_title($this->input->get_post("acc_name"), "underscore", TRUE),
								"acc_city_id" => $this->input->get_post("acc_city_id"),
								"acc_latitude" => (($this->input->get_post("acc_latitude"))?($this->input->get_post("acc_latitude")):(NULL)),
								"acc_longitude" => (($this->input->get_post("acc_longitude"))?($this->input->get_post("acc_longitude")):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->accomodation->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->accomodation->insert($insUpd);
							}
							
							// ins
							$getAcc2ins_majIds = $this->acc2ins_maj->getAcc2ins_majIds($where = "a2im_acc_id = '".$this->input->get_post("ID")."' and a2im_ins_id is not null");

							$deletedInsId = array();
							foreach($getAcc2ins_majIds as $a2imId => $a2imData) {
								$this->acc2ins_maj->delete($a2imId);
								$deletedInsId[$a2imData["a2imInsId"]] = $a2imData["a2imInsId"];
							}
							if($this->input->post("ins_id")) {
								foreach($this->input->post("ins_id") as $insId) {
									if($insId) {
										$this->acc2ins_maj->insert(array("a2im_acc_id" => $this->input->get_post("ID"), "a2im_ins_id" => $insId));
										if(isset($deletedInsId[$insId])) unset($deletedInsId[$insId]);
									}
								}
							}
							
							// major - acc kötések rendberakása
							if(count($deletedInsId)) {
								$this->acc2ins_maj->deleteAcc2ins_byDeletedInsIds($deletedInsId);
							}

							if(!defined("AUTH_ERROR")) {
								$this->entity_category_insert_update($this->input->post("ENTITY"), abs($this->input->get_post("ID")));
							}
						}
					}
				} break;

				case "SCH": {
					if($this->input->get_post("del")) {
						$this->scholarship->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("sch_name")) {
							$response["error"] .= $this->lang->line("THE_SCHOLARSHIP_NAME_IS_REQUIRED")."<br/>";
						}

						if(!(($this->input->get_post("ins_id") and isset($_POST["ins_id"][0]) and $_POST["ins_id"][0]) or ($this->input->get_post("maj_id") and isset($_POST["maj_id"][0]) and $_POST["maj_id"][0]))) {
							$response["error"] .= $this->lang->line("SET_AT_LEAST_ONE_INSTITUTE_OR_MAJOR")."<br/>";
						}
						
						if(!$response["error"]) {

							$tmp_url_name = $url_name = my_url_title($this->input->get_post("sch_name"), "underscore", TRUE);
							$free = FALSE;
							$counter = 1;
							while(!$free) {
								$free = TRUE;
								$getScholarship = $this->scholarship->getScholarship($where = "sch_url_name = '".$this->db->escape_str($url_name)."'".(($this->input->get_post("ID") > 0)?(" and sch_id <> '".$this->db->escape_str($this->input->get_post("ID"))."' "):("")));
								if($getScholarship) {
									$free = FALSE;
									$url_name = $tmp_url_name.$counter;
									$counter++;
								}
							}

							$insUpd = array(
								"sch_name" => $this->input->get_post("sch_name"),
								"sch_url_name" => $url_name,
								"sch_sub_id" => (($this->input->get_post("sch_sub_id"))?($this->input->get_post("sch_sub_id")):(NULL)),
								"sch_list_date" => (($this->input->get_post("sch_list_date"))?(Common::dateToDatabase($this->input->get_post("sch_list_date"))):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->scholarship->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->scholarship->insert($insUpd);
							}
							
							// sch2 tabla torlese es feltoltese
							$getScholarship = $this->scholarship->getScholarship("sch_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
							foreach(array("ins", "cou", "maj") as $entity) {
								if(!isset($_POST[$entity."_id"]) or !is_array($_POST[$entity."_id"])) {
									$_POST[$_POST[$entity."_id"]] = array();
								}
								if(isset($getScholarship[0][strtoupper($entity)])) {
									foreach($getScholarship[0][strtoupper($entity)] as $entId => $entData) {
										if(!in_array($entId, $this->input->post($entity."_id"))) {
											// delete
											$this->sch2cou_ins_maj->delete($entData["s2cId"]);
										}
									}
								}
								
								foreach($this->input->post($entity."_id") as $entId) {
									if($entId and !isset($getScholarship[0][strtoupper($entity)][$entId])) {
										// insert
										$this->sch2cou_ins_maj->insert(array(
											"s2c_sch_id" => $this->input->get_post("ID"),
											"s2c_".$entity."_id" => $entId,
										));
									}
								}
								
							}

							if(!defined("AUTH_ERROR")) {
								$this->entity_category_insert_update($this->input->post("ENTITY"), abs($this->input->get_post("ID")));
							}
							
						}
					}
				} break;

				case "USER": {
					if($this->input->get_post("del")) {
						$this->user->delete($this->input->get_post("ID"));
					} else {
						if($this->input->get_post("usr_email")) {
							$getUser = $this->user->getUser($where = "usr_email = '".$this->db->escape_str($this->input->get_post("usr_email"))."' and usr_id <> '".$this->db->escape_str($this->input->get_post("ID"))."'");
							if($getUser) {
								$response["error"] .= $this->lang->line("THE_E-MAIL_ADDRESS_IS_RESERVED_PLEASE_SELECT_AN_OTHER")."<br/>";
							}
							if(!preg_match("/^[^0-9][A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/i", $this->input->post("usr_email"))) {
								$response["error"] .= $this->lang->line("THE_FORMAT_OF_THE_E-MAIL_ADDRESS_IS_INCORRECT")."<br/>";
							}
						} else {
							$response["error"] .= $this->lang->line("E-MAIL_ADDRESS_IS_REQUIRED")."<br/>";
						}

						if($this->input->get_post("ID") < 0 and !$this->input->get_post("usr_password")) {
							$response["error"] .= $this->lang->line("PASSWORD_IS_REQUIRED")."<br/>";
						}

						if($this->input->get_post("usr_password") and $this->input->get_post("usr_password") <> $this->input->get_post("usr_password_re")) {
							$response["error"] .= $this->lang->line("THE_ENTERED_PASSWORDS_ARE_NOT_THE_SAME")."<br/>";
						}

						if(!$response["error"]) {
							$insUpd["usr_email"] = $this->input->get_post("usr_email");
							if($this->input->get_post("usr_password")) {
								$insUpd["usr_password"] = md5($this->input->get_post("usr_password"));
							}
							if($this->input->get_post("ID") > 0) {
								$this->user->update($this->input->get_post("ID"), $insUpd);
								$usrId = $this->input->get_post("ID");
							} else {
								if(is_array($this->session->userdata("grpName")) and Common::isAdmin()) {
									$insUpd["usr_createdby_grp_id"] = "2";
								}
								$insUpd["usr_registered"] = Common::now();
								$usrId = $_POST["ID"] = $this->user->insert($insUpd);
							}

							$getUsr2grp = $this->usr2grp->getUsr2grp($where = "u2g_usr_id = '".$usrId."'");
							$groupChangeFromNonverified2Admin = 0;
							
							foreach($getUsr2grp as $grp_id => $u2g_id) {
								$this->usr2grp->delete($u2g_id);
								if($grp_id == 3) {
									$groupChangeFromNonverified2Admin++;
								}
							}

							$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$usrId."'");
							foreach($getUsr2ent as $ENTITY => $d) {
								if(in_array($ENTITY, array("COU", "CITY"))) {
									foreach($d["u2eIds"] as $u2e_id) {
										$this->usr2ent->delete($u2e_id);
									}
								} elseif($ENTITY == "INS") {
									if(!is_array($this->input->post("ins_id"))) {
										$_POST["ins_id"] = array();
									}
									foreach($d["children"] as $ii => $insId) {
										if(!in_array($insId, $this->input->post("ins_id"))) {
											$this->usr2ent->delete($d["u2eIds"][$ii]);
											foreach($getUsr2ent as $innerEntity => $innerD) {
												if(substr($innerEntity, 0, 8) == "PAGE_CAT") {
													foreach($innerD["u2eIds"] as $innerInsId => $innerU2eId) {
														if($insId == $innerInsId) {
															$this->usr2ent->delete($innerU2eId);
														}
													}
												}
											}
										}
									}
								}
							}

							$u2eInsert = FALSE;

							if($this->input->post("cou_id")) {
								foreach($this->input->post("cou_id") as $couId) {
									if($couId) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_cou_id" => $couId));
										$u2eInsert = TRUE;
									}
								}
							}

							if($this->input->post("city_id")) {
								foreach($this->input->post("city_id") as $cityId) {
									if($cityId) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_city_id" => $cityId));
										$u2eInsert = TRUE;
									}
								}
							}

							if($this->input->post("ins_id")) {
								foreach($this->input->post("ins_id") as $insId) {
									if($insId and !in_array($insId, ((isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array())))) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_ins_id" => $insId));
										$u2eInsert = TRUE;
									}
								}
							}

							if($this->input->post("page_cat")) {
								foreach($this->input->post("page_cat") as $page_cat_name) {
									if($page_cat_name) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_page_cat" => $page_cat_name));
										$u2eInsert = TRUE;
									}
								}
							}

							if($u2eInsert or $this->input->post("u2g_grp_id")) {
								// ID -2 (Admin)
								$u2g_grp_id = ($this->input->post("u2g_grp_id")?$this->input->post("u2g_grp_id"):2);
								$this->usr2grp->insert(array("u2g_usr_id" => $usrId, "u2g_grp_id" => $u2g_grp_id));
								if($u2g_grp_id == 2) {
									$groupChangeFromNonverified2Admin++;
								}
							}
							
							// not verfied adminból, vagy nem admin userból admin user lett
							if($groupChangeFromNonverified2Admin > 1) {
								$getUser = $this->user->getUser("usr_id = '".intval($usrId)."'");
								Common::sendEmail($getUser[$usrId]["usrEmail"], $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_SUBJECT"), $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_BODY"), $replace = NULL, $attach = NULL);
							}

						}

					}
				} break;

			}

		}

		if($response["error"]) {
			echo	"\$('#editorError').html('".$this->db->escape_str($response["error"])."').show('fast');";
			echo	"
					$('#studyEditorModal').animate({
						scrollTop: $('#studyEditorModal').offset().top
					}, 1000);
					";
		}

	}

	function entity_category_insert_update($entity, $id) {
		$getEnt2cat = $this->ent2cat->getEnt2cat($where = "e2c_entity = '".$this->db->escape_str($entity)."' and e2c_ent_id = '".$this->db->escape_str($id)."' ");
		// clean html attributes
		foreach($_POST as $key => $val) {
			if(preg_match("/cat_[0-9]*/msi", $key) and trim(strip_tags($val))) {
				$catId = mb_substr($key, 4);
				$_POST["cat_".$catId] = $this->input->post("cat_".$catId, TRUE);
				$_POST["cat_".$catId] = preg_replace('/class=".*?"/', '', $_POST["cat_".$catId]);
				$_POST["cat_".$catId] = preg_replace('/style=".*?"/', '', $_POST["cat_".$catId]);
				$_POST["cat_".$catId] = preg_replace('/id=".*?"/', '', $_POST["cat_".$catId]);
			}
			// date overwrite
			if(preg_match("/cat_[0-9]*_day/msi", $key)) {
				$catId = mb_substr($key, 4, strlen($key)-8);
				// day
				$_POST["cat_".$catId."_day"] = intval($_POST["cat_".$catId."_day"]);
				if($_POST["cat_".$catId."_day"] >= 1 and $_POST["cat_".$catId."_day"] <= 31) {
					$_POST["cat_".$catId."_day"] = str_pad($_POST["cat_".$catId."_day"], 2, 0, STR_PAD_LEFT);
				} else {
					$_POST["cat_".$catId."_day"] = "";
				}
				// month
				$_POST["cat_".$catId."_month"] = intval($_POST["cat_".$catId."_month"]);
				if($_POST["cat_".$catId."_month"] >= 1 and $_POST["cat_".$catId."_month"] <= 12) {
					$_POST["cat_".$catId."_month"] = str_pad($_POST["cat_".$catId."_month"], 2, 0, STR_PAD_LEFT);
				} else {
					$_POST["cat_".$catId."_month"] = "";
				}
				// year
				$_POST["cat_".$catId."_year"] = intval($_POST["cat_".$catId."_year"]);
				
				if(!checkdate ( intval($_POST["cat_".$catId."_month"]) , intval($_POST["cat_".$catId."_day"]) , intval($_POST["cat_".$catId."_year"]) )) {
					$_POST["cat_".$catId."_day"] = "";
				}
				
				$_POST["cat_".$catId] = (($this->input->post("cat_".$catId."_month"))?($this->input->post("cat_".$catId."_month")."."):("")) . (($this->input->post("cat_".$catId."_day"))?($this->input->post("cat_".$catId."_day")."."):("")) . $this->input->post("cat_".$catId."_year");
				unset($_POST["cat_".$catId."_day"]);
				unset($_POST["cat_".$catId."_month"]);
				unset($_POST["cat_".$catId."_year"]);
			}
		}
		
		foreach($getEnt2cat as $catId => $catData) {
			if(!$this->input->post("cat_".$catId)) {
				$this->ent2cat->delete($catData["e2cId"]);
			} else {
				$insUpd = array (
					"e2c_temp" => (($entity == "USER")?(NULL):(($this->input->post("cat_".$catId)))),
					"e2c_temp_flag" => (($entity == "USER")?("N"):("I")),
				);
				if($entity == "USER") {
					$insUpd["e2c_text"] = $this->input->post("cat_".$catId);
				}
				$this->ent2cat->update($catData["e2cId"], $insUpd);
			}
		}
		foreach($_POST as $key => $val) {
			if(preg_match("/cat_[0-9]*/msi", $key) and trim(strip_tags($val))) {
				$catId = mb_substr($key, 4);
				if(!isset($getEnt2cat[$catId])) {
					$insUpd = array(
						"e2c_entity" => $entity,
						"e2c_ent_id" => $id,
						"e2c_cat_id" =>	$catId,
						"e2c_temp" => (($entity == "USER")?(NULL):($this->input->post("cat_".$catId))),
						"e2c_text" => (($entity != "USER")?(NULL):($this->input->post("cat_".$catId))),
						"e2c_temp_flag" => (($entity == "USER")?("N"):("I")),
					);
					$this->ent2cat->insert($insUpd);
				}
			}
		}
	}

	function get_institute_addresses() {
		$this->page["instituteAddressList"] = $this->institute_address->addressMapper($this->institute_address->where("add_ins_id", $this->input->post("insId"))->getAll());
		$this->page["institute"] = $this->institute->getById($this->input->post("insId"));
		$this->load->view("admin/addresses_lte", $this->page);
	}

	function get_institute_address_editor() {
		if($this->input->post("addId") > 0) {
			$this->page["institute_address"] = $this->institute_address->getById($this->input->post("addId"));
		} else {
			$this->page["institute"] = $this->institute->getById($this->input->post("insId"));
			$this->page["institute_address"] = new stdClass();
			$this->page["institute_address"]->add_city_id = $this->page["institute"]->ins_city_id;
		}
		$this->load->view("admin/editortemplate/institute_address", $this->page);
	}

	function institute_address_insert_update() {

		if($this->input->post("del")) {
			$this->institute_address->delete($this->input->post("addId"));
		} else {

			$response = array("error" => "");

			if (!$this->input->get_post("add_city_id")) {
				$response["error"] .= $this->lang->line("CITY_IS_REQUIRED");
			}

			if (!$this->input->get_post("add_name")) {
				$response["error"] .= ($response["error"] ? "<br/>" : "") . $this->lang->line("ADDRESS_NAME_IS_REQUIRED");
			}

			if (!$this->input->get_post("add_address")) {
				$response["error"] .= ($response["error"] ? "<br/>" : "") . $this->lang->line("ADDRESS_IS_REQUIRED");
			}

			if (!$response["error"]) {
				$insUpd = array(
					"add_ins_id" => $this->input->post("add_ins_id"),
					"add_name" => $this->input->post("add_name"),
					"add_city_id" => $this->input->post("add_city_id"),
					"add_postal_code" => $this->input->post("add_postal_code"),
					"add_address" => $this->input->post("add_address"),
					"add_latitude" => $this->input->post("add_latitude"),
					"add_longitude" => $this->input->post("add_longitude"),
				);
				if ($this->input->post("add_id") > 0) {
					$this->institute_address->update($this->input->post("add_id"), $insUpd);
				} else {
					$this->institute_address->insert($insUpd);
				}

			} else {
				echo "\$('#editorError').html('" . $this->db->escape_str($response["error"]) . "').show('fast');";
				echo "
					$('#studyEditorModal').animate({
						scrollTop: $('#studyEditorModal').offset().top
					}, 1000);
					";
				return;
			}
		}

		echo "
			$('#studyEditorModal').modal('toggle');
			$('[data-address-ins=" . $this->input->post("add_ins_id") . "]').trigger('click');
			";
	}

	function get_ent2image() {
		$ENTITY = $this->input->post("ENTITY");
		$ID = $this->input->post("ID");
		$this->page["getEnt2image"] = array();
		if(in_array($ENTITY, array("COU", "CITY", "INS", "MAJ", "ACC", "SCH"))) {
			$this->page["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_".strtolower($ENTITY)."_id = '".$this->db->escape_str($ID)."'");
		}
		$this->load->view("admin/images_lte", $this->page);
	}

	function ent2image_insert_update() {
		if($this->input->get_post("del")) {
			$ids = preg_split("/\|/", $this->input->post("e2iId"));
			foreach($ids as $e2iId) {
				$this->ent2image->delete($e2iId);
			}
			echo	"imageDisplayRefresh();";
		} elseif($this->input->get_post("copy") and $this->input->get_post("e2iId")) {
			if(!is_array($this->input->get_post("e2iId"))) {
				$_POST["e2iId"] = array($this->input->get_post("e2iId"));
			}
			$getEnt2image_copy = $this->ent2image->getEnt2image("e2i_id in (".implode(",", $this->input->get_post("e2iId")).")");
			if(count($getEnt2image_copy)) {
				$getEnt2image = $this->ent2image->getEnt2image("e2i_".strtolower($this->input->get_post("ENTITY"))."_id = ".intval($this->input->get_post("ID")));
				foreach($getEnt2image_copy as $e2i_copy) {
					$isset = FALSE;
					foreach($getEnt2image as $e2i) {
						if($e2i_copy["e2iHash"] == $e2i["e2iHash"]) {
							$isset = TRUE;
						}
					}
					if(!$isset) {
						$this->ent2image->insert(array(
							"e2i_".strtolower($this->input->get_post("ENTITY"))."_id" => $this->input->get_post("ID"),
							"e2i_image_name" => $e2i_copy["e2iImageName"],
							"e2i_image_name_original" => $e2i_copy["e2iImageNameOriginal"],
							"e2i_width" => $e2i_copy["e2iWidth"],
							"e2i_height" => $e2i_copy["e2iHeight"],
							"e2i_thumb_width" => $e2i_copy["e2iThumbWidth"],
							"e2i_thumb_height" => $e2i_copy["e2iThumbHeight"],
							"e2i_resized_width" => $e2i_copy["e2iResizedWidth"],
							"e2i_resized_height" => $e2i_copy["e2iResizedHeight"],
							"e2i_hash" => $e2i_copy["e2iHash"],
						));
					}
				}
			}
		} else {
			$this->ent2image->update($this->input->post("e2iId"), array("e2i_alt" => $this->input->post("e2i_alt")));
			echo	"\$('#studyEditorModal').modal('toggle');";
			echo	"imageDisplayRefresh();";
		}
	}

	function image_crop($e2iId = NULL) {
		if(!is_null($e2iId)) {
			$getEnt2image = $this->ent2image->getEnt2image($where = "e2i_id = '".$this->db->escape_str($e2iId)."'");
			if(count($getEnt2image)) {
				if($this->input->post("remove")) {
					$this->ent2image->update($getEnt2image[0]["e2iId"], array("e2i_cropped" => "N"));
				} else {
					$img = BASEPATH."..".UPLOADS.$getEnt2image[0]["e2iImageNameResized"];

					$config['image_library'] = 'gd2';
					$config['source_image'] = $img;
					$config['maintain_ratio'] = FALSE;
					$newimg = $config['new_image'] = str_replace("_resized", "_cropped", BASEPATH."..".UPLOADS.$getEnt2image[0]["e2iImageNameResized"]);
					$config['width'] = $this->input->post("width");
					$config['height'] = $this->input->post("height");
					$config['x_axis'] = $this->input->post("x");
					$config['y_axis'] = $this->input->post("y");
					$this->load->library('image_lib', $config);
					if($this->image_lib->crop()) {
						$this->ent2image->update($getEnt2image[0]["e2iId"], array("e2i_cropped" => "I"));
					}

					if($this->input->post("width") != 660 or $this->input->post("height") != 350) {	
						$config['image_library'] = 'gd2';
						$config['source_image'] = $newimg;
						$config['maintain_ratio'] = FALSE;
						$config['width'] = 660;
						$config['height'] = 350;
						$config['new_image'] = $newimg;
						$this->image_lib->initialize($config);
						$this->image_lib->resize();
					}

				}

			}
		}
		echo	"\$('#studyEditorModal').modal('toggle');";
		echo	"imageDisplayRefresh();";
	}

	function file_upload() {
		if(!$this->input->post("ENTITY") or !in_array($this->input->post("ENTITY"), array("COU", "CITY", "INS", "MAJ","ACC", "SCH", "MAIN_SLIDER")) or !is_numeric($this->input->post("ID"))) {
			return FALSE;
		}

		$response["success"] = false;
		$response["error"] = "";
		$save_path = $_SERVER["DOCUMENT_ROOT"].str_replace("media", "uploads", MEDIA);
		$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';
		$MAX_FILENAME_LENGTH = 260;

		$max_file_size_in_bytes = 2147483647; // 2GB in bytes
		$upload_name = 'Filedata';

		$POST_MAX_SIZE = ini_get('post_max_size');
		$unit = strtoupper(substr($POST_MAX_SIZE, -1));
		$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

		if((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
			$response["error"] .= $this->lang->line("POST_EXCEEDED_MAXIMUM_ALLOWED_SIZE");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("POST_EXCEEDED_MAXIMUM_ALLOWED_SIZE")).'}');
		}

		// Other variables
		$file_name = '';
		$uploadErrors = array(
			0 => $this->lang->line("THERE_IS_NO_ERROR_THE_FILE_UPLOADED_WITH_SUCCESS"),
			1 => $this->lang->line("THE_UPLOADED_FILE_EXCEEDS_THE_UPLOAD_MAX_FILESIZE_DIRECTIVE"),
			2 => $this->lang->line("THE_UPLOADED_FILE_EXCEEDS_THE_MAX_FILE_SIZE_DIRECTIVE_THAT_WAS_SPECIFIED_IN_THE_HTML_FORM"),
			3 => $this->lang->line("THE_UPLOADED_FILE_WAS_ONLY_PARTIALLY_UPLOADED"),
			4 => $this->lang->line("NO_FILE_WAS_UPLOADED"),
			6 => $this->lang->line("MISSING_A_TEMPORARY_FOLDER")
		);

		// Validate the upload
		if (!isset($_FILES[$upload_name])) {
			$response["error"] .= $this->lang->line("NO_UPLOAD_FOUND");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("NO_UPLOAD_FOUND")).'}');
		} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
			$response["error"] .= $uploadErrors[$_FILES[$upload_name]["error"]];
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($uploadErrors[$_FILES[$upload_name]["error"]]).'}');
		} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
			$response["error"] .= $this->lang->line("UPLOAD_FAILED_IS_UPLOADED_FILE_TEST");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("UPLOAD_FAILED_IS_UPLOADED_FILE_TEST")).'}');
		} else if (!isset($_FILES[$upload_name]['name'])) {
			$response["error"] .= $this->lang->line("FILE_HAS_NO_NAME");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("FILE_HAS_NO_NAME")).'}');
		}

		// Validate the file size (Warning: the largest files supported by this code is 2GB)
		$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
		if (!$file_size || $file_size > $max_file_size_in_bytes) {
			$response["error"] .= $this->lang->line("FILE_EXCEEDS_THE_MAXIMUM_ALLOWED_SIZE");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("FILE_EXCEEDS_THE_MAXIMUM_ALLOWED_SIZE")).'}');
		}

		if ($file_size <= 0) {
			$response["error"] .= $this->lang->line("FILE_SIZE_OUTSIDE_ALLOWED_LOWER_BOUND");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("FILE_SIZE_OUTSIDE_ALLOWED_LOWER_BOUND")).'}');
		}

		$rand = mt_rand()."_".uniqid("", TRUE);

		$path_info = pathinfo($_FILES[$upload_name]["name"]);
		$file_extension = $path_info["extension"];

		$file_name = $this->input->post("ENTITY")."_".$this->input->post("ID")."_".$rand.".".$file_extension;
		//Common::pr(getimagesize($_FILES[$upload_name]["tmp_name"]));

		list($width, $height, $type, $attr)= getimagesize($_FILES[$upload_name]["tmp_name"]);
		if(!$width) {
			$response["error"] .= $this->lang->line("INVALID_FILE_FORMAT");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("INVALID_FILE_FORMAT")).'}');
		}

		if(!$height or $height < 110) {
			$response["error"] .= $this->lang->line("INVALID_FILE_FORMAT");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("INVALID_FILE_FORMAT")).'}');
		}

		if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
			$response["error"] .= $this->lang->line("FILE_COULD_NOT_BE_SAVED");
			die(json_encode($response));
			//die('{success:false,error:'.json_encode($this->lang->line("FILE_COULD_NOT_BE_SAVED")." - ".$save_path.$file_name).'}');
		} else {
			$file_hash = md5(file_get_contents($save_path.$file_name));
			
			// thumb
			$config['image_library'] = 'gd2';
			$config['source_image'] = $save_path.$file_name;
			$config['create_thumb'] = TRUE;
			$config['maintain_ratio'] = TRUE;
			$config['master_dim'] = 'height';
			$config['width'] = 180;
			$config['height'] = 110;
			$this->load->library('image_lib', $config);
			$this->image_lib->resize();

			$thumb = preg_split("/\./", $file_name);
			$len = strlen($thumb[count($thumb)-1]);
			list($thumbwidth, $thumbheight, $type, $attr) = getimagesize(base_url().UPLOADS.substr($file_name, 0, -($len+1))."_thumb.".$thumb[count($thumb)-1]);

			$this->image_lib->clear();
			$config = array();

			// resize
			$config['image_library'] = 'gd2';
			$config['source_image'] = $save_path.$file_name;
			$config['maintain_ratio'] = TRUE;
			if($width > 900 or $height > 500) {
				$config['width'] = 900;
				$config['height'] = 500;
			} else {
				$config['width'] = $width;
				$config['height'] = $height;
			}
			$config['thumb_marker'] = "_resized";
			$this->image_lib->initialize($config);
			$this->image_lib->resize();
			list($resizedwidth, $resizedheight, $type, $attr) = getimagesize(base_url().UPLOADS.substr($file_name, 0, -($len+1))."_resized.".$thumb[count($thumb)-1]);

			$e2iId = $this->ent2image->insert(array(
				"e2i_".strtolower($this->input->post("ENTITY"))."_id" => $this->input->post("ID"),
				"e2i_hash" => $file_hash,
				"e2i_image_name_original" => basename($_FILES[$upload_name]['name']),
				"e2i_image_name" => $file_name,
				"e2i_width" => $width,
				"e2i_height" => $height,
				"e2i_thumb_width" => $thumbwidth,
				"e2i_thumb_height" => $thumbheight,
				"e2i_resized_width" => $resizedwidth,
				"e2i_resized_height" => $resizedheight,
			));

		}

		if($response["error"]) {
			echo	json_encode($response);
		} else {
			echo	json_encode(array("success" => true));
		}

	}

	function get_city() {
		define("OVERRIDE", TRUE);
		if($this->input->get("id")) {
			$where = "city_id = ".intval($this->input->get("id"));
		} else {
			$where = "city_name like '%".$this->db->escape_str($this->input->get("q"))."%'";
		}
		$getCity = $this->city->getCity($where);
		$ret = array();
		foreach($getCity as $city) {
			$ret[] = array(
				"id" => $city["cityId"],
				"text" => $city["cityName"]. " (".$city["couName"].")",
			);
		}
		echo	json_encode($ret);
	}

	function get_country() {
		if(!defined("OVERRIDE"))
			define("OVERRIDE", TRUE);
		$getCountry = $this->country->getCountry();
		$ret = array();
		foreach($getCountry as $cou) {
			$ret[$cou["couId"]] = $cou["couName"];
		}
		return $ret;
	}

	function get_currency() {
		$getCurrency = $this->currency->getCurrency();
		$ret = array();
		foreach($getCurrency as $curr) {
			$ret[] = array(
				"id" => $curr["currId"],
				"text" => $curr["currText"],
			);
		}
		echo	json_encode($ret);
	}

	function get_accomodation($obj = FALSE) {
		$where = NULL;
		if($this->input->get("insId")) $where = "a2im_ins_id = '".intval($this->input->get("insId"))."'";
		if($this->input->post("id")) $where = ($where ? " and " : "") . "a2im_acc_id = '".intval($this->input->get("id"))."'";
		$getAccomodation = $this->accomodation->getAccomodation($where);
		$ret = array();
		foreach($getAccomodation as $acc) {
			$ret[] = array(
				"id" => $acc["accId"],
				"text" => $acc["accName"],
			);
		}
		echo	json_encode($ret);
	}

	function get_szotar($type = NULL, $progType = NULL) {
		if($this->input->get_post("progType")) $progType = $this->input->get_post("progType");
		switch($type) {
			case "PROGTYPE_2": {
				$szotar = Common::szotar(array("PROGTYPE_2"));
				if($progType == "LS") {
					unset($szotar["PROGTYPE_2"]["FD"]);
					unset($szotar["PROGTYPE_2"]["AYS"]);
				}
				$ret = array();
				foreach($szotar["PROGTYPE_2"] as $szoSname => $szoLname) {
					$ret[] = array(
						"id" => $szoSname,
						"text" => $szoLname,
					);
				}
				echo	json_encode($ret);
			} break;
		}
	}

	function get_ent2image_template() {
		$this->load->view("admin/editortemplate/ent2image", null);
	}

	function messages($mesUniqueId = null) {

		$this->page["lte_title"] = $this->lang->line("MESSAGES");
		if(Common::isSuperAdmin()) {
			$this->page["getMessage"] = $this->message->getMessage();
		} else { 
			$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."'");
			$getUsr2entINS = (($getUsr2ent and isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array()));
			$where = "";
			if($mesUniqueId) {
				$where = "mes_unique_id = ".intval($mesUniqueId);
			}
			$this->page["getMessage"] = $this->message->getMessage($where = ($where ? $where . " and " : "") . "(mes_sender_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."' ".((count($getUsr2entINS))?(" or mes_ins_id in (".implode(",", $getUsr2entINS).")"):(""))." )");
			//common::pr($this->page["getMessage"]); exit;
		}
		
		if(!is_null($mesUniqueId)) {
			$this->page["mesUniqueId"] = $mesUniqueId;
			$this->page["breadcrumb"]["admin_lte/messages"] = $this->page["lte_title"];
			$this->page["lte_title"] = $this->lang->line("VIEW_MESSAGE_TIMELINE");

			// readdate karbantartas
			if(!Common::isSuperAdmin()) {
				foreach($this->page["getMessage"] as $messages) {
					foreach($messages as $message) {
						if(!$message["mesReaderUsrId"] and $message["mesSenderUsrId"] != $this->session->userdata("usrId")) {
							$this->message->update($message["mesId"],
								array(
									"mes_reader_usr_id" => $this->session->userdata("usrId"),
									"mes_readdate" => Common::now(),
								) 
							);
						}
					}
				}
			}

		}

		$this->page["content"] .= $this->load->view("admin/messages_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function message_edit() {
		$this->page["getMessage"] = $this->message->getMessage("mes_id = '".$this->db->escape_str($this->input->post("ID"))."'");
		if($this->page["getMessage"]) {
			$this->page["getMessage"] = current($this->page["getMessage"]);
		} else {
			$this->page["getMessage"] = array(
				array(
					"mesId" => "",
					"mesInsId" => $this->input->post("mesInsId"),
					"mesUniqueId" => $this->input->post("mesUniqueId"),
				)
			);
		}
		$this->load->view("admin/editortemplate/message", $this->page);
	}

	function articles($artPosition = NULL) {
		if(!(Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_ART")))
			redirect("admin_lte");

		$where = NULL;
		if(!is_null($artPosition)) {
			if($artPosition == "I") {
				$where = "art_highlight = '".$this->db->escape_str($artPosition)."'";
			} else {
				$where = "art_position = '".$this->db->escape_str($artPosition)."'";
			}
		}
		$this->page["lte_title"] = $this->lang->line("ARTICLES");
		$this->page["articleList"] = $this->article_model->getArticle($where);

		$this->page["content"] .= $this->load->view("admin/articles_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function articles_sort() {
		if(!(Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_ART")))
			redirect("admin_lte");

		$where = NULL;
		$artPosition = $this->input->post("artPosition");
		if(!is_null($artPosition)) {
			if($artPosition == "I") {
				$where = "art_highlight = '".$this->db->escape_str($artPosition)."'";
			} else {
				$where = "art_position = '".$this->db->escape_str($artPosition)."'";
			}
		}
		$this->page["artPosition"] = $artPosition;
		$this->page["articleList"] = $this->article_model->getArticle($where, $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "artOrder", $dir = "ASC");

		$this->load->view("admin/articles_sort_lte", $this->page);
	}

	function article_edit() {
		$this->page["getArticle"] = $this->article_model->getArticle("art_id = '".$this->db->escape_str($this->input->post("ID"))."'");
		$this->page["getCountryList"] = $this->get_country();

		$getInstituteList = $this->institute->getInstitute();
		foreach($getInstituteList as $ins) {
			$this->page["getInstituteList"][$ins["insId"]] = $ins["insName"]." (".$ins["cityName"]." - ".$ins["couName"].")";
		}

		$this->page["getSubjectList"] = $this->subject->getSubject();

		$majorList = $this->major->getMajor();
		$this->page["majorList"] = array();
		foreach($majorList as $maj) {
			$this->page["majorList"][$maj["majId"]] = $maj["majName"]." (".$maj["insName"].")";
		}

		$this->load->view("admin/editortemplate/article", $this->page);
	}

	function article_insert_update() {
		if(!Common::isAdminJog("PAGE_CAT_ART")) redirect("admin/index");
		$response = array("error" => "");
		
		if($this->input->get_post("publish") !== FALSE) {

			$getArticleById = $this->article_model->getArticleById($this->input->get_post("ID"));
			$getEnt2artByArtId = $this->ent2art->getEnt2artByArtId($this->input->get_post("ID"));
			
			switch($this->input->get_post("publish")) {
				// töröl unpublished
				case "0": {
					// ekkor töröljük
					if(!$getArticleById->art_name) {
						$this->article_model->delete($this->input->get_post("ID"));
						foreach($getEnt2artByArtId as $ent2art) {
							$this->ent2art->delete($ent2art->e2a_id);
						}
					} else {
						$insUpd = array(
							"art_name_temp" => NULL,
							"art_url_name_temp" => NULL,
							"art_lead_temp" => NULL,
							"art_text_temp" => NULL,
							"art_highlight_temp" => NULL,
							"art_position_temp" => NULL,
							"art_temp_flag" => "N",
						);
						$this->article_model->update($this->input->get_post("ID"), $insUpd);
						foreach($getEnt2artByArtId as $ent2art) {
							if($ent2art->e2a_temp_flag == "I") {
								$this->ent2art->delete($ent2art->e2a_id);
							}
						}
					}
				} break;
				// publish
				case "1": {
					$insUpd = array(
						"art_name_temp" => NULL,
						"art_url_name_temp" => NULL,
						"art_lead_temp" => NULL,
						"art_text_temp" => NULL,
						"art_highlight_temp" => NULL,
						"art_position_temp" => NULL,
						"art_temp_flag" => "N",
						"art_name" => $getArticleById->art_name_temp,
						"art_url_name" => $getArticleById->art_url_name_temp,
						"art_lead" => $getArticleById->art_lead_temp,
						"art_text" => $getArticleById->art_text_temp,
						"art_highlight" => $getArticleById->art_highlight_temp,
						"art_position" => $getArticleById->art_position_temp,
					);
					$this->article_model->update($this->input->get_post("ID"), $insUpd);
					foreach($getEnt2artByArtId as $ent2art) {
						if($ent2art->e2a_temp_flag == "N") {
							$this->ent2art->delete($ent2art->e2a_id);
						} else {
							$this->ent2art->update($ent2art->e2a_id, array("e2a_temp_flag" => "N"));
						}
					}
				} break;
				// töröl published
				case "2": {
					$insUpd = array(
						"art_name_temp" => Common::coalesce(array($getArticleById->art_name, $getArticleById->art_name_temp)),
						"art_url_name_temp" => Common::coalesce(array($getArticleById->art_url_name, $getArticleById->art_url_name_temp)),
						"art_lead_temp" => Common::coalesce(array($getArticleById->art_lead, $getArticleById->art_lead_temp)),
						"art_text_temp" => Common::coalesce(array($getArticleById->art_text, $getArticleById->art_text_temp)),
						"art_highlight_temp" => Common::coalesce(array($getArticleById->art_highlight, $getArticleById->art_highlight_temp)),
						"art_position_temp" => Common::coalesce(array($getArticleById->art_position, $getArticleById->art_position_temp)),
						"art_name" => NULL,
						"art_temp_flag" => "I",
					);
					$this->article_model->update($this->input->get_post("ID"), $insUpd);
					foreach($getEnt2artByArtId as $ent2art) {
						if($ent2art->e2a_temp_flag == "N") {
							$vanTemp = FALSE;
							foreach($getEnt2artByArtId as $ent2art2) {
								if($ent2art->e2a_cou_id == $ent2art2->e2a_cou_id and $ent2art->e2a_city_id == $ent2art2->e2a_city_id and $ent2art->e2a_ins_id == $ent2art2->e2a_ins_id and $ent2art->e2a_maj_id == $ent2art2->e2a_maj_id and $ent2art->e2a_sub_id == $ent2art2->e2a_sub_id and $ent2art2->e2a_temp_flag == "I") {
									$vanTemp = TRUE;
								}
							}
							if(!$vanTemp) {
								$this->ent2art->update($ent2art->e2a_id, array("e2a_temp_flag" => "I"));
							} else {
								$this->ent2art->delete($ent2art->e2a_id);
							}
						}
					}
				} break;
			}
			
			//Common::pr($getArticleById); Common::pr($getEnt2artByArtId);

		} else {
		
			if($this->input->get_post("del")) {
				$this->article_model->delete($this->input->get_post("artId"));
			} elseif($this->input->get_post("sort") and intval($this->input->get_post("position"))) {
				if($this->input->post("artPosition") == "I") {
					$where = "art_highlight = '".$this->db->escape_str($this->input->post("artPosition"))."'";
				} else {
					$where = "art_position = '".$this->db->escape_str($this->input->post("artPosition"))."'";
				}
				$getArticle = $this->article_model->getArticle($where);
				foreach($getArticle as $art) {
					if($art["artId"] == $this->input->post("ID")) {
						$this->article_model->update($art["artId"], array("art_order" => $this->input->post("position")));
						$oldOrder = $art["artOrder"];
					}
				}
				if(isset($oldOrder)) {
					foreach($getArticle as $art) {
						if($art["artOrder"] == $this->input->post("position")) {
							$this->article_model->update($art["artId"], array("art_order" => $oldOrder));
						}
					}
				}
			} else {
				$csat = array("sub", "cou", "city", "ins", "maj");
				
				if(Common::isAdmin()) {
					$vanCsatolas = FALSE;
					foreach($csat as $ent) {
						$post_ent = $this->input->get_post($ent."_id");
						if($post_ent and isset($post_ent[0]) and ($post_ent[0])) {
							$vanCsatolas = TRUE;
						}
					}
					if(!$vanCsatolas) {
						$response["error"] .= $this->lang->line("SET_AT_LEAST_ONE_LINK");
					}
				}
				
				if(!$response["error"]) {

					$tmp_url_name = $url_name = my_url_title($this->input->get_post("art_name"), "underscore", TRUE);
					$free = FALSE;
					$counter = 1;
					while(!$free) {
						$free = TRUE;
						$getArticle = $this->article_model->getArticle($where = "art_url_name = '".$this->db->escape_str($url_name)."'".(($this->input->get_post("art_id"))?(" and art_id <> '".$this->db->escape_str($this->input->get_post("art_id"))."' "):("")));
						if($getArticle) {
							$free = FALSE;
							$url_name = $tmp_url_name.$counter;
							$counter++;
						}
					}

					$szotar = Common::szotar("ARTPOS");
					// kiemelt cikk csak centerben lehet
					if(in_array($this->input->get_post("art_position"), array("F", "H", "R"))) {
						$_POST["art_highlight"] = "N";
					}
					$insUpd = array(
						"art_name_temp" => $this->input->get_post("art_name"),
						"art_url_name_temp" => $url_name,
						"art_lead_temp" => $this->input->get_post("art_lead"),
						"art_text_temp" => $this->input->get_post("art_text"),
						"art_position_temp" => ((in_array($this->input->get_post("art_position"), array_keys($szotar["ARTPOS"])))?($this->input->get_post("art_position")):("C")),
						"art_highlight_temp" => $this->input->get_post("art_highlight")?$this->input->get_post("art_highlight"):"N",
						"art_temp_flag" => "I",
						"art_usr_id" => $this->session->userdata("usrId"),
					);
					if($this->input->get_post("art_id")) {
						$this->article_model->update($this->input->get_post("art_id"), $insUpd);
						$artId = $this->input->get_post("art_id");
					} else {
						$insUpd["art_createtime"] = Common::now();
						$insUpd["art_url_name"] = $url_name;
						//$insUpd["art_name"] = $this->input->get_post("art_name");
						$artId = $this->article_model->insert($insUpd);
					}
					/* Csatolasok mentese */
					$getEnt2art = $this->ent2art->getEnt2art($where = "e2a_art_id = '".intval($artId)."' and e2a_temp_flag = 'I'");
					foreach($csat as $ent) {
						if($this->input->get_post($ent."_id") and count($this->input->get_post($ent."_id"))) {
							foreach($this->input->get_post($ent."_id") as $ID) {
								if($ID and (!isset($getEnt2art[$artId][$ent]) or !in_array($ID, $getEnt2art[$artId][$ent]))) {
									$this->ent2art->insert(array("e2a_art_id" => $artId, "e2a_temp_flag" => "I", "e2a_".$ent."_id" => $ID));
								}
							}
						}
						if(isset($getEnt2art[$artId][$ent])) {
							foreach($getEnt2art[$artId][$ent] as $e2aId => $ID) {
								if(!in_array($ID, $this->input->get_post($ent."_id"))) {
									$this->ent2art->delete($e2aId);
								}
							}
						}
					}
					
				}
			}
		
		}
		//echo	json_encode(array("success" => true) + $response);

		if($response["error"]) {
			echo	"\$('#editorError').html('".$this->db->escape_str($response["error"])."').show('fast');";
			echo	"
					$('#studyEditorModal').animate({
						scrollTop: $('#studyEditorModal').offset().top
					}, 1000);
					";
		}

		if(Common::isSuperAdmin()) {
			$this->article_model->fixOrder();
		}
	}

	function users($type = "Admin") {
		$tgetUser = $this->user->getUser($where = ((!is_null($type) and $type == "Admin")?("u2g_usr_id is not null"):("u2g_usr_id is null")), $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		$this->page["userList"] = array();
		if($tgetUser) {
			foreach($tgetUser as $d) {
				$this->page["userList"][] = $d;
			}
		}
		$this->page["lte_title"] = $this->lang->line(Common::isAdmin() ? "ADMINISTRATORS" : "USERS");
		$this->page["content"] .= $this->load->view("admin/users_lte", $this->page, TRUE);
		$this->load->view("template/admin_lte_page", $this->page);
	}

	function password_change() {
		$this->load->view("admin/password_change_lte");
	}

	function password_change_insert_update() {
		$response = array("error" => "");

		if(!$this->input->get_post("usr_password")) {
			$response["error"] .= $this->lang->line("PASSWORD_IS_REQUIRED");
		}

		if($this->input->get_post("usr_password") and $this->input->get_post("usr_password") <> $this->input->get_post("usr_password_re")) {
			$response["error"] .= $this->lang->line("THE_ENTERED_PASSWORDS_ARE_NOT_THE_SAME");
		}

		if(!$response["error"]) {
			if($this->input->get_post("usr_password")) {
				$insUpd["usr_password"] = md5($this->input->get_post("usr_password"));
			}
			$this->user->update($this->session->userdata("usrId"), $insUpd);
			echo	"
					$('#studyEditorModal').modal('toggle');
					$('#studyDisplayModal .modal-title').html('".$this->lang->line("PASSWORD_CHANGED")."');
					$('#studyDisplayModal .modal-body').html('".$this->db->escape_str($this->lang->line("YOUR_PASSWORD_CHANGED_SUCCESSFULLY"))."');
					$('#studyDisplayModal').modal('toggle');
					";
		} else {
			echo	"\$('#editorError').html('".$this->db->escape_str($response["error"])."').show('fast');";
			echo	"
					$('#studyEditorModal').animate({
						scrollTop: $('#studyEditorModal').offset().top
					}, 1000);
					";
		}

	}

	function get_page_category($return = FALSE) {
		$szotar = Common::szotar("ENTITY");
		if(isset($szotar["ENTITY"])) {
			$pageCat = array();
			//if(Common::isAdminJog("PAGE_CAT", "IMP")) 
			$pageCat["IMP"] = $szotar["ENTITY"]["IMP"];
			//if(Common::isAdminJog("PAGE_CAT", "MAJ")) 
			$pageCat["MAJ"] = $szotar["ENTITY"]["MAJ"];
			//if(Common::isAdminJog("PAGE_CAT", "SCH")) 
			$pageCat["SCH"] = $szotar["ENTITY"]["SCH"];
			//if(Common::isAdminJog("PAGE_CAT", "WAS")) 
			$pageCat["WAS"] = $szotar["ENTITY"]["WAS"];
			//if(Common::isAdminJog("PAGE_CAT", "INT")) 
			$pageCat["INT"] = $szotar["ENTITY"]["INT"];
			//if(Common::isAdminJog("PAGE_CAT", "ACC")) 
			$pageCat["ACC"] = $szotar["ENTITY"]["ACC"];
			//if(Common::isAdminJog("PAGE_CAT", "ART")) 
			$pageCat["ART"] = $szotar["ENTITY"]["ART"];
			//if(Common::isAdminJog("PAGE_CAT", "FAC")) 
			$pageCat["FAC"] = $szotar["ENTITY"]["FAC"];
			if($return) return $pageCat;

			else echo Common::arr2jsobj($pageCat, $keytoobj = TRUE);
		}
	}

	function user_privileges() {
		$this->page["getPageCategory"] = $this->get_page_category($return = TRUE);
		$this->page["getUsr2ent"] = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->input->post("ID"))."'");
		if(isset($this->page["getUsr2ent"]["INS"]["children"])) {
				$strHelp = "";
				define("OVERRIDE", TRUE);
				$this->page["getInstituteList"] = $this->institute->getInstitute("ins_id in (".implode(", ", $this->page["getUsr2ent"]["INS"]["children"]).")");
				$this->load->view("admin/user_privilege_lte", $this->page);
		} else {
			echo	"
					<br/><div class=\"alert alert-info alert-dismissable\">
						<i class=\"fa fa-info\"></i>
						<button aria-hidden=\"true\" data-dismiss=\"alert\" class=\"close\" type=\"button\">×</button>
						".$this->lang->line("PRIVILEGES_DOESNT_EXISTS")."
					</div>
					";
		}
	}

	function usr2ent_insert_update() {
		if(intval($this->input->post("usrId")) == $this->session->userdata("usrId")) {
			echo json_encode(array("error" => $this->lang->line("YOU_CANNOT_EDIT_YOUR_OWN_PRIVILEGES")));
			echo	"\$('#displayError').remove();";
			echo	"\$('#studyDisplayModal .modal-body').prepend('<div id=\"displayError\">".$this->db->escape_str($this->lang->line("YOU_CANNOT_EDIT_YOUR_OWN_PRIVILEGES"))."</div>')";
			echo	"
					$('#studyDisplayModal').animate({
						scrollTop: $('#studyDisplayModal').offset().top
					}, 1000);
					";
			return;
		}
		if($this->user->getUser("usr_id = '".intval($this->input->post("usrId"))."'")) {
			$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->input->post("usrId"))."'");
			if(isset($getUsr2ent["PAGE_CAT_".$this->input->post("ENTITY")]["u2eIds"][$this->input->post("insId")]) and $this->input->post("checked") == 0) {
				$this->usr2ent->delete($getUsr2ent["PAGE_CAT_".$this->input->post("ENTITY")]["u2eIds"][$this->input->post("insId")]);
			} elseif(!isset($getUsr2ent["PAGE_CAT_".$this->input->post("ENTITY")]["u2eIds"][$this->input->post("insId")])) {
				$this->usr2ent->insert(array(
					"u2e_usr_id" => $this->input->post("usrId"),
					"u2e_ins_id" => $this->input->post("insId"),
					"u2e_page_cat" => $this->input->post("ENTITY"),
				));
			}
		}
	}

	function email_send_form() {
		$this->load->view("admin/email_send_lte");
	}

	function email_send() {
		$response = array("error" => "");

		if(!$this->input->get_post("subject")) {
			$response["error"] .= $this->lang->line("EMAIL_SUBJECT_IS_REQUIRED");
		}

		if(!$this->input->get_post("text")) {
			$response["error"] .= " ".$this->lang->line("TEXT_OF_THE_MESSAGE_IS_REQUIRED");
		}

		if(!$response["error"] and preg_match("/^[^0-9][A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/i", $this->input->get_post("email"))) {
			$response["message"] = Common::sendEmail($this->input->get_post("email"), $this->input->get_post("subject"), $this->input->get_post("text"));
		}

		if($response["error"]) {
			echo	"\$('#editorError').html('".$this->db->escape_str($response["error"])."').show('fast');";
			echo	"
					$('#studyEditorModal').animate({
						scrollTop: $('#studyEditorModal').offset().top
					}, 1000);
					";
		} else {
			echo	"
			$('#studyEditorModal').modal('toggle');
			$('#studyDisplayModal .modal-title').html('".$this->lang->line("MESSAGE_SENT")."');
			$('#studyDisplayModal .modal-body').html('".$this->db->escape_str($this->lang->line("MESSAGE_IS_SUCCESSFULLY_SENT_TO_THE_USER"))."');
			$('#studyDisplayModal').modal('toggle');
			";
		}
	}

	// nem megerositett admin atkerulese admin csoportba
	function usr2grp_insert_update() {
		$getUser = $this->user->getUser($where = "u2g_usr_id is not null");
		if(isset($getUser[$this->input->get_post("usrId")])) {
		
			$getUsr2grp = $this->usr2grp->getUsr2grp($where = "u2g_usr_id = '".$this->input->get_post("usrId")."'");
			foreach($getUsr2grp as $u2g_id) {
				$this->usr2grp->delete($u2g_id);
			}
			$this->usr2grp->insert(array("u2g_usr_id" => $this->input->get_post("usrId"), "u2g_grp_id" => 2));

			$getUser = $this->user->getUser("usr_id = '".intval($this->input->get_post("usrId"))."'");
			Common::sendEmail($getUser[intval($this->input->get_post("usrId"))]["usrEmail"], $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_SUBJECT"), $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_BODY"), $replace = array("<FULL_NAME>" => (($getUser[intval($this->input->get_post("usrId"))]["fullName"])?($getUser[intval($this->input->get_post("usrId"))]["fullName"]):($getUser[intval($this->input->get_post("usrId"))]["usrEmail"]))), $attach = NULL);
			
			if($this->input->get_post("insId")) {
				$this->usr2ent->insert(array("u2e_usr_id" => $this->input->get_post("usrId"), "u2e_ins_id" => $this->input->get_post("insId")));
			}
			
		}
	}

}
